package com.market2.utils.converter.impl;

import com.market2.dto.SwapDto;
import com.market2.model.Investisseur;
import com.market2.model.Societe;
import com.market2.model.Swap;
import com.market2.utils.converter.Converter;

public class SwapConverter extends Converter
{
	@SuppressWarnings("unchecked") @Override
	public SwapDto convertTo(Object source)
	{
		if(source == null || !(source instanceof Swap)) {
			return null;
		}
		
		Swap swap = (Swap) source;
		SwapDto dto = new SwapDto();
		
		dto.setNumero(swap.getNumero());
		dto.setValeurUnitaire(swap.getValeurUnitaire());
		dto.setQuantite(swap.getQuantite());
		
		if(swap.getTitulaire() != null) {
			dto.setTitulaire(swap.getTitulaire().getLogin());
		}
		
		if(swap.getSociete() != null) {
			dto.setSociete(swap.getSociete().getNom());
		}
		
		dto.setStartDate(swap.getStartDate());
		dto.setEndDate(swap.getEndDate());
		dto.setFirstCounterparty(swap.getFirstCounterparty());
		dto.setSecondCounterparty(swap.getSecondCounterparty());
		
		return dto;
	}

	@SuppressWarnings("unchecked") @Override
	public Swap convertFrom(Object source)
	{
		if(source == null || !(source instanceof SwapDto)) {
			return null;
		}
		
		SwapDto dto = (SwapDto) source;
		Swap swap = new Swap();
		
		swap.setNumero(dto.getNumero());
		swap.setValeurUnitaire(dto.getValeurUnitaire());
		swap.setQuantite(dto.getQuantite());
		
		Investisseur titulaire = getEntityManager().find(Investisseur.class, dto.getTitulaire());
		swap.setTitulaire(titulaire);
		
		Societe societe = getEntityManager().find(Societe.class, dto.getSociete());
		swap.setSociete(societe);
		
		swap.setStartDate(dto.getStartDate());
		swap.setEndDate(dto.getEndDate());
		
		swap.setFirstCounterparty(dto.getFirstCounterparty());
		swap.setSecondCounterparty(dto.getSecondCounterparty());
		
		return swap;
	}

}
